package wiki.kaizen.cloud.shiro.stateless.config;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.DefaultSessionStorageEvaluator;
import org.apache.shiro.mgt.DefaultSubjectDAO;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.SubjectContext;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.mgt.DefaultWebSubjectFactory;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import wiki.kaizen.cloud.shiro.stateless.shiro.StatelessRealm;

/**
 * 管理器配置类
 * @author  xeepoo
 * */
@Configuration
public class ManagerConfig {


    /**
     * 无状态 realm
     */
    @Bean
    public StatelessRealm statelessRealm(){
        return  new StatelessRealm();
    }
    /**
     * 会话管理类 禁用session
     * @return
     */
    public DefaultWebSessionManager defaultSessionManager(){
        DefaultWebSessionManager manager = new DefaultWebSessionManager();
        manager.setSessionValidationSchedulerEnabled(false);
        return manager;
    }
    /**
     * 安全管理类
     * @param statelessRealm
     */
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(StatelessRealm statelessRealm){
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();

        //禁用sessionStorage
        DefaultSubjectDAO de = (DefaultSubjectDAO)manager.getSubjectDAO();
        DefaultSessionStorageEvaluator defaultSessionStorageEvaluator =(DefaultSessionStorageEvaluator)de.getSessionStorageEvaluator();
        defaultSessionStorageEvaluator.setSessionStorageEnabled(false);

        manager.setRealm(statelessRealm);

        //无状态subject，禁止创建session
        manager.setSubjectFactory(
            new DefaultWebSubjectFactory(){
                @Override
                public Subject createSubject(SubjectContext context) {
                    context.setSessionCreationEnabled(false);
                    return super.createSubject(context);
                }
            }
        );

        manager.setSessionManager(defaultSessionManager());
        //设置了SecurityManager采用使用SecurityUtils的静态方法 获取用户等
        SecurityUtils.setSecurityManager(manager);
        return manager;
    }
}
